<?php

namespace app\common\model;

use think\Model;
use think\Db;
use think\Config;

class Teacher extends Model
{

    

    

    // 表名
    protected $name = 'teacher';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'subject_text',
        'grade_text',
        'age_range_text',
    ];


    public static function getLists($params = [])
    {
        extract($params);

        $condition = [
            'deletetime' => Db::raw('deletetime IS NULL')
        ];
        if(!isset($per_page)){
            $per_page = 10;
        }
        if(isset($where)){
            $condition = array_merge($where,$condition);
        }
        if(isset($settled)){
            if($settled==4 || $settled==5){
                $settled_cn = self::get_settled_cn_by_key($settled);
                $condition['exp'] = Db::raw('find_in_set(\''.$settled_cn.'\',`settled_type`)');
            }else{
                $settled_cn = self::get_settled_cn_by_key($settled);
                $condition['exp'] = Db::raw('find_in_set(\''.$settled_cn.'\',`settled_type`)');
            }
        }
        if(isset($recommend)){
            $condition['recommend'] = 1;
        }
        if(isset($keyword)){
            $subject_by_keyword = Db::name('subject')->where([
                'name' => $keyword
            ])->value('id');
            if($subject_by_keyword){
                $subject = $subject_by_keyword;
            }else{
                $condition['nickname'] = ['like','%'.$keyword.'%'];
            }
        }
        if(isset($age_range) && $age_range!==''){
            $condition['age_range_id'] = $age_range;
        }
        if(isset($grade) && $grade!==''){
            $grade_name = (new Grade())->where([
                'id' => $grade
            ])->value('name');
            if($grade_name!=='不限'){
                $condition['grade_id'] = $grade;
            }
        }
        if(isset($subject) && $subject!==''){
            $subject_name = (new Subject())->where([
                'id' => $subject
            ])->value('name');
            if($subject_name!=='不限'){
                $condition['subject_id'] = $subject;
            }
        }
        if(isset($sex) && $sex!=='' && $sex!=='不限'){
            $condition['sex'] = $sex;
        }
        $field = '*';
        if(isset($lat) && $lat && isset($lng) && $lng){
//            $field = '*,round(6378.138*2*asin(sqrt(pow(sin( (unholiday_area_lat*pi()/180-' . $lat . '*pi()/180)/2),2)+cos(unholiday_area_lat*pi()/180)*cos(' . $lat . '*pi()/180)* pow(sin( (holiday_area_lng*pi()/180-' . $lng . '*pi()/180)/2),2))),1) AS distance';
            $field = "*,ROUND( ST_Distance_Sphere( POINT(" . $lng . ", " . $lat . "), POINT(unholiday_area_lng, unholiday_area_lat) ) / 1000, 1) AS distance";
        }
        $order = 'weigh desc,star desc';
        if(isset($distance) && $distance!=='' && isset($lat) && $lat && isset($lng) && $lng){
            if($distance!=='不限'){
                $distance = str_replace('km', '', $distance);
                $order = 'distance asc';
                $per_page = 10000;
            }else{
                $distance = '';
            }
        }
        $list = self::where($condition)->field($field)->order($order);

//        return $list->fetchSql(true)->select();
        if(isset($page)){
            $list = $list->paginate($per_page);
        }else{
            if(isset($limit)){
                $list = $list->limit(0,$limit)->select();
            }else{
                $list = $list->select();
            }
        }

        foreach ($list as $k => &$v) {
            $v = self::oneRowExtend($v);
            if(isset($distance) && $distance!==''){
                if($v['distance']>$distance){
                    unset($list[$k]);
                }
            }
            $with = $v['with'];
            if($with['unholiday_areas']){
                $unholiday_areas = str_replace('区','',$with['unholiday_areas']);
                $unholiday_areas = explode(',',$unholiday_areas);
                if(count($unholiday_areas)==1){
                    $with['unholiday_areas'] = $unholiday_areas[0];
                }elseif(count($unholiday_areas)==2){
                    $with['unholiday_areas'] = $unholiday_areas[0].'/'.$unholiday_areas[1];
                }elseif(count($unholiday_areas)==3){
                    $with['unholiday_areas'] = $unholiday_areas[0].'/'.$unholiday_areas[1].'/'.$unholiday_areas[2];
                }else{
                    $with['unholiday_areas'] = $unholiday_areas[0].'/'.$unholiday_areas[1].'/'.$unholiday_areas[2].'...';
                }
            }else{
                $unholiday_pick = explode(' ',$with['unholiday_pick']);
                $with['unholiday_areas'] = $unholiday_pick[1];
            }
            //正常情况下都是显示寒暑假区域，但是在寒暑假兼职家教列表里，显示的是寒暑假的区域，前端固定用的是unholiday_areas这个字段，对调一下就好了
            if(isset($settled) && $settled==3){

                if($with['holiday_areas']){
                    $holiday_areas = str_replace('区','',$with['holiday_areas']);
                    $holiday_areas = explode(',',$holiday_areas);
                    if(count($holiday_areas)==1){
                        $with['unholiday_areas'] = $holiday_areas[0];
                    }elseif(count($holiday_areas)==2){
                        $with['unholiday_areas'] = $holiday_areas[0].'/'.$holiday_areas[1];
                    }elseif(count($holiday_areas)==3){
                        $with['unholiday_areas'] = $holiday_areas[0].'/'.$holiday_areas[1].'/'.$holiday_areas[2];
                    }else{
                        $with['unholiday_areas'] = $holiday_areas[0].'/'.$holiday_areas[1].'/'.$holiday_areas[2].'...';
                    }
                }else{
                    $holiday_pick = explode(' ',$with['holiday_pick']);
                    $with['unholiday_areas'] = $holiday_pick[1];
                }
            }
            $v['with'] = $with;
            if($v['age_range_id']){
                $v['age_range_advise'] = Db::name('age_range')->where(['id' => $v['age_range_id']])->value('advise_price');
            }
        }
        return $list;
    }

    public static function oneRowExtend($data)
    {
        //这里一直在纠结到底是用健来管理还是用值来管理
//        $settled_config_free_list = json_decode(Config::get('site.settled_type_free'));
//        $settled_config_list = json_decode(Config::get('site.settled_type_free'));
//        $settled_config_list = array_merge($settled_config_list,$settled_config_free_list);

        $TeacherAudit = new TeacherAudit();
        $with = $TeacherAudit->order('id desc')->where([
            'user_id'=>$data['user_id'],
            'status'=>2
        ])
            //todo 这里调用了全部属性不大合理
//            ->field(' teaching_method, settled_type_free, settled_type, nickname, realname, sex, school_name, education, profession, give_time, photo_images, teacher_age, tags, teacher_exp ')
            ->find();

        if($with['holiday_pick']){
            $holiday_pick = explode(' ',$with['holiday_pick']);
            $with['holiday_pick'] = $holiday_pick[0].' '.$holiday_pick[1];
        }else{
            $with['holiday_pick'] = '';
        }

        if($with['unholiday_pick']){
            $unholiday_pick = explode(' ',$with['unholiday_pick']);
            $with['unholiday_pick'] = $unholiday_pick[0].' '.$unholiday_pick[1];
        }else{
            $with['unholiday_pick'] = '';
        }

        $with['teaching_method'] = explode(',',$with['teaching_method']);
        if($data['teacher_age']){
            $with['teacher_age'] = $data['teacher_age'];
        }
//        $settled_type = explode(',',$data['settled_type']);
//        $settled_type_values = [];
//        foreach ($settled_type as $v){
//            $settled_type_values[] = $settled_config_list[$v-1];
//        }
        $data['settled_type'] = explode(',',$data['settled_type']);
        if(count($data['settled_type'])>=2){
            $data['settled_type_for_list'] = ['专职教学家教'];
        }else{
            $data['settled_type_for_list'] = $data['settled_type'];
        }
        $give_lessons = json_decode($with['give_lessons'],true);
        $gl_subject = '';
        $gl_age_range = [];
        $gl_first_subject = '';
        if(isset($give_lessons[0])){
            $age_range_id = Db::name('grade')->where(['id' => $give_lessons[0]['grade']])->value('age_range_id');
            $age_range_name = Db::name('age_range')->where([
                'id' => $age_range_id
            ])->value('name');
            $gl_age_range[] = $age_range_name;
            $gl_first_subject = $gl_subject = $give_lessons[0]['subject_cn'];
        }
        $data['test'] = $age_range_id;

        if(isset($give_lessons[1])){
            if($give_lessons[1]['subject_cn']==$gl_first_subject){
                $age_range_id = Db::name('grade')->where(['id' => $give_lessons[1]['grade']])->value('age_range_id');
                $age_range_name = Db::name('age_range')->where([
                    'id' => $age_range_id
                ])->value('name');
                $gl_age_range[] = $age_range_name;

            }
        }

        if(isset($give_lessons[2])){
            if($give_lessons[2]['subject_cn']==$gl_first_subject){
                $age_range_id = Db::name('grade')->where(['id' => $give_lessons[2]['grade']])->value('age_range_id');
                $age_range_name = Db::name('age_range')->where([
                    'id' => $age_range_id
                ])->value('name');
                $gl_age_range[] = $age_range_name;
            }
        }
        $gl_age_range = array_unique($gl_age_range);
        $gl_age_range = implode('/',$gl_age_range);



        $data['give_lessons'] = $gl_age_range .' | '. $gl_subject;
        $data['with'] = $with;
        return $data;
    }

    public static function get_settled_cn_by_key($key)
    {
        $settled_config_free_list = json_decode(Config::get('site.settled_type_free'));
        $settled_config_list = json_decode(Config::get('site.settled_type'));
        $settled_config_list = array_merge($settled_config_free_list,$settled_config_list);
        return $settled_config_list[$key-1];
    }
    


    public function getSubjectTextAttr($value, $data){
        $name = (new Subject)->where(['id' => $data['subject_id']])->value('name');
        return $name;
    }

    public function getGradeTextAttr($value, $data){
        $name = (new Grade)->where(['id' => $data['grade_id']])->value('name');
        return $name;
    }

    public function getAgeRangeTextAttr($value, $data){
        $name = (new AgeRange)->where(['id' => $data['age_range_id']])->value('name');
        return $name;
    }

    public function user()
    {
        return $this->belongsTo('\app\admin\model\xykeep\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function audit()
    {
        return $this->belongsTo('\app\common\model\TeacherAudit', 'audit_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }





}
